package com.hang.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Slf4j
public class JwtUtil {
    //token的过期时间(开发时默认30天到期)
    private static long tokenExpiration = 24L*60L*60L*1000L*30L;
    //token的签名密钥
    private static String tokenSignKey = "123456";

    public static String createToken(Long uid, String name) {

        Algorithm algorithm = Algorithm.HMAC256(tokenSignKey);
        Date expirationDate = new Date(System.currentTimeMillis()+tokenExpiration);

        //生成token
        return  JWT.create()
                    .withClaim("userId", uid)
                    .withClaim("realName",name)
                    .withExpiresAt(expirationDate)
                    .sign(algorithm);
    }
    public static Long getUserId(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenSignKey)).build();
        DecodedJWT decode = verifier.verify(token);
        return decode.getClaim("userId").asLong();
    }
    public static String getUserName(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenSignKey)).build();
        DecodedJWT decode = verifier.verify(token);
        return decode.getClaim("realName").asString();
    }

    /**
     * 校验是否过期，过期返回true
     * @return
     * @author 廖煜航
     * @date 2022-11-20
     */
    public static boolean isExpires(String token){
        if(ObjectUtils.isEmpty(token)){
            return true;
        }
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenSignKey)).build();
        try {
            verifier.verify(token);
        }catch (JWTVerificationException e){
            return true;
        }
        return false;
    }

    /**
     * 验证token
     * @param token
     * @return
     * @author 廖煜航
     * @date 2022-11-20
     */
    public static void verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(tokenSignKey)).build().verify(token);  // 如果验证通过，则不会报错，否则会抛出异常
        }catch (NullPointerException npe){
//            log.error("token无效");
        }
    }
}
